package com.acme.bankapp;

import com.acme.bankapp.domain.Bank;
import com.acme.bankapp.domain.Client;
import com.acme.bankapp.domain.account.AbstractAccount;
import com.acme.bankapp.domain.account.Account;
import com.acme.bankapp.exception.BankException;

import java.io.*;

/**
* Created by Student on 21.11.2014.
*/

public class BankDataLoaderService {

    public static void saveBank(Bank bank, String fileName) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileName));
        bufferedWriter.write(String.valueOf(bank.getClients().length));
        bufferedWriter.newLine();
        for (Client client : bank.getClients()) {
            assert client != null;
            bufferedWriter.write(client.toJSONString());
            bufferedWriter.newLine();
            bufferedWriter.write(String.valueOf(client.getAccounts().length));
            bufferedWriter.newLine();
            for (Account account : client.getAccounts()) {
                assert account != null;
                bufferedWriter.write(account.toJSONString());
                bufferedWriter.newLine();
            }
        }
        bufferedWriter.flush();
    }

    public static Bank loadBank(String fileName) throws BankException, IOException {
        Bank bank = new Bank();
        BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
        int clientsNumber = Integer.parseInt(bufferedReader.readLine());
        for (int i = 0; i < clientsNumber; i++) {
            Client client = Client.parseJSON(bufferedReader.readLine());
            bank.addClient(client);
            int accountsNumber = Integer.parseInt(bufferedReader.readLine());
            for (int j = 0; j < accountsNumber; j++) {
                client.addAccount(AbstractAccount.parseJSON(bufferedReader.readLine()));
            }
        }
        return bank;
    }
}
